package com.mytool.service;

import com.mytool.convert.TableConvert;
import com.mytool.domain.TableDomain;
import com.mytool.model.GenerateCodeReq;
import com.mytool.model.TableMetaData;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class GenerateCodeHelper {

    public static String outFilepath(Map<String, Object> dataModel, String filename, String fileContent) {
        switch (filename) {
            case "controller.ftl":
                return convertJavaFilepath(dataModel, "adapter", filename, fileContent);
        }
        return null;
    }

    static String convertJavaFilepath(Map<String, Object> dataModel, String level, String filename, String fileContent) {
        String firstLine = readFirstLine(fileContent);
        String packagePath = parsePackagePath(StringUtils.trimAllWhitespace(firstLine));
        String filepath = dataModel.get("serviceName") + "-" + level + "/" + packagePath;
        filepath = filepath + "/" + dataModel.get("domainObjectName") + StringUtils.capitalize(filename.replace(".ftl", ".java"));
        return filepath;
    }

    static String parsePackagePath(String firstLine) {
        firstLine = firstLine.replace("package", "").replace(";","");
        return firstLine.replaceAll("\\.", "/");
    }
    public final static TableDomain parseDdl(String ddlSql) {
        try {
            CreateTable createTable = (CreateTable) CCJSqlParserUtil.parse(ddlSql);
            TableDomain tableDomain = new TableDomain(createTable);
            return tableDomain;
        } catch (JSQLParserException e) {
            log.error("parse error:", e);
        }
        return null;
    }

    public final static Map<String, Object> prepareDataModel(GenerateCodeReq req, TableDomain tableMetaData) {
        Map<String, Object> dataModel = new HashMap<>(16);
        dataModel.put("serviceName", req.getServiceName());
        dataModel.put("module", req.getModule());
        dataModel.put("function", req.getFunction());
        dataModel.put("packagePrefix", req.getPackagePrefix());
        dataModel.put("tableName", tableMetaData.getTableName());
        dataModel.put("domainObjectName", tableMetaData.getDomainObjectName());
        dataModel.put("fieldObjectName", StringUtils.uncapitalize(tableMetaData.getDomainObjectName()));
        dataModel.put("entityComment", tableMetaData.getTableComment());
        List<Map<String, String>> fields = new ArrayList<>();
        tableMetaData.getColumns().stream().forEach(it -> {
            Map<String,String> field = new HashMap<>();
            field.put("name", it.getColumnName());
            field.put("columnName", it.getColumnName());
            field.put("type", it.getColumnType());
            field.put("javaType", it.getJavaTypeStr());
            field.put("comment", it.getColumnComment());
            fields.add(field);
        });
        dataModel.put("fields", fields);
        return dataModel;
    }

    static String readFirstLine(String fileContent) {
        try (BufferedReader reader = new BufferedReader(new StringReader(fileContent))) {
            String firstLine = reader.readLine(); // 读取第一行
            return firstLine;
        } catch (Exception e) {
            log.error("read file error:", e);
        }
        return null;
    }
}
